package com.teacher.ellio;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import androidx.annotation.NonNull;
import com.teacher.game.framework.util.InputHandler;
import com.teacher.game.framework.util.Painter;
import com.teacher.game.framework.util.PerformanceMonitor;
import com.teacher.game.framework.util.MemoryLeakDetector;
import com.teacher.game.framework.util.PerformanceValidator;
import com.teacher.game.state.LoadState;
import com.teacher.game.state.State;

public class GameView extends SurfaceView implements Runnable {

    private Bitmap gameImage;
    private Rect gameImageSrc, getGameImageDst;
    private Canvas canvas;
    private Painter g;

    private Thread gameThread;
    private boolean running;
    
    // 性能监控
    private PerformanceMonitor performanceMonitor;
    private MemoryLeakDetector memoryLeakDetector;
    private PerformanceValidator performanceValidator;


    public GameView(Context context,int gameWidth,int gameHeight){
        super(context);

        gameImage = Bitmap.createBitmap(gameWidth, gameHeight, Bitmap.Config.RGB_565);
        gameImageSrc = new Rect(0, 0, gameWidth, gameHeight);
        getGameImageDst = new Rect();
        canvas = new Canvas(gameImage);
        g = new Painter(canvas);
        
        // 初始化性能监控
        performanceMonitor = PerformanceMonitor.getInstance();
        memoryLeakDetector = MemoryLeakDetector.getInstance();
        performanceValidator = PerformanceValidator.getInstance();
        
        // 跟踪GameView对象
        memoryLeakDetector.trackObject("GameView", this);

        SurfaceHolder holder = getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
                Log.d("GameView", "surfaceCreated");
                initInput();
                if (currentState==null)
                    setCurrState(new LoadState());
                
                // 开始性能验证测试（30秒）
                performanceValidator.startValidation(30);
                
                initGame();
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
                Log.d("GameView", "surfaceDestroyed");
                pauseGame();
            }
        });
    }

    private InputHandler inputHandler;

    private void initInput(){
        if (inputHandler==null)
            inputHandler=new InputHandler();
        this.setOnTouchListener(inputHandler);
    }

    private volatile State currentState;

    public void setCurrState(State newState) {
        System.gc();
        newState.init();
        currentState = newState;
        inputHandler.setCurrentState(newState);
    }

    @Override
    public void run() {
        long updateDurationMillis=0;
        long sleepDurationMillis=0;
        while (running){
            long beforeUpdateAndRender=System.nanoTime();
            long deltaMillis=updateDurationMillis+sleepDurationMillis;
            updateAndRender(deltaMillis);
            updateDurationMillis=(System.nanoTime()-beforeUpdateAndRender)/1000000;
            sleepDurationMillis=Math.max(17-updateDurationMillis,2);
            try {
                Thread.sleep(sleepDurationMillis);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }

    private void updateAndRender(long deltaMillis) {
        // 帧开始性能监控
        performanceMonitor.frameStart();
        
        // 更新游戏状态
        currentState.update(deltaMillis/1000f);
        
        // 渲染游戏内容
        currentState.render(g);
        renderGameImage();
        
        // 内存泄漏检测（定期执行）
        memoryLeakDetector.performLeakCheck();
        
        // 性能验证记录
        performanceValidator.recordFrame();
        
        // 帧结束性能监控
        performanceMonitor.frameEnd();
    }

    private void renderGameImage() {
        Canvas canvas = getHolder().lockCanvas();
        if (canvas != null) {
            canvas.getClipBounds(getGameImageDst);
            canvas.drawBitmap(gameImage, gameImageSrc, getGameImageDst, null);
            getHolder().unlockCanvasAndPost(canvas);
        }
    }


    private void initGame(){
        running = true;
        gameThread = new Thread(this,"游戏线程");
        gameThread.start();
    }

    private void pauseGame(){
        running = false;
        while (gameThread.isAlive()){
            try {
                gameThread.join();
                break;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        
        // 清理资源和停止性能监控
        cleanup();
    }
    
    /**
     * 清理资源
     */
    private void cleanup() {
        Log.d("GameView", "开始清理游戏资源...");
        
        // 输出性能报告
        Log.d("GameView", performanceMonitor.getPerformanceReport());
        Log.d("GameView", memoryLeakDetector.getLeakReport());
        
        // 停止跟踪GameView对象
        memoryLeakDetector.untrackObject("GameView", this);
        
        // 强制垃圾回收
        memoryLeakDetector.forceGarbageCollection();
        
        // 释放Assets资源
        Assets.releaseAll();
        
        Log.d("GameView", "游戏资源清理完成");
    }
}
